import { createRouter, createWebHistory } from 'vue-router'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'home',
      component: () => import('@/views/home/HomeView.vue'),
      meta: {
        title: '首页',
        loginRequired: true
      }
    },
    {
      path: '/list',
      name: 'list',
      component: () => import('@/views/list/ListView.vue'),
      meta: {
        title: '列表',
        loginRequired: true
      }
    },
    {
      path: '/center',
      name: 'center',
      component: () => import('@/views/center/CenterView.vue'),
      meta: {
        title: '个人中心',
        loginRequired: true
      }
    },
    {
      path: '/:pathMatch(.*)*',
      name: 'notfound',
      component: () => import('@/views/NotFound.vue'),
      meta: {
        title: '404页面不存在',
        loginRequired: true
      }
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('@/views/login/LoginView.vue'),
      meta: {
        title: '登录页面'
      }
    }
  ],
})

router.beforeEach((to) => {
  // console.log(to)
  // 判断meta字段的loginRequired
  if (to.meta.loginRequired) {
    // 从本地存储中读取token
    const token: string | null = localStorage.getItem('token')
    // 判断token是否存在
    if (!token) return '/login'
  }
  // 如果meta字段中有title, 修改文档的标题
  if (to.meta.title) {
    console.log(typeof to.meta.title)
    document.title = to.meta.title as string
  }
})

export default router
